package com.yonyou.cn.mongodbtest;

import com.google.common.collect.Sets;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.reactivestreams.client.*;

import com.yonyou.cn.mongodbtest.utils.SubscriberUtils;
import org.bson.Document;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class Test {


    public static volatile Set<Long> set = Sets.newConcurrentHashSet();
     static AtomicLong counter = new AtomicLong(0);
//    static volatile Long counter = 0L ;

//    public static void main(String[] args) throws InterruptedException {
//        /*for (int i = 0; i < 5; i++) {
//            Thread r1 = new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    for (int j = 0; j < 100; j++) {
//                        long l = counter.incrementAndGet();
////                            long l = counter++;
//                        System.out.println(Thread.currentThread().getName()+"数字："+l);
////                        System.out.println(Thread.currentThread().getName()+"数字："+counter++);
//                        set.add(l);
//
//                    }
//
//                }
//            });
//            r1.start();
//        }
//        Thread.sleep(2000);
//        System.out.println(set.size());*/
////        System.out.println(3*0.1);
//
//
//
//    }

    public static void mainss(String[] args) throws Exception{
        //服务器实例表
        List servers = new ArrayList();
        servers.add(new ServerAddress("10.10.65.6", 28017));

        //配置构建器
        MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder();
        MongoCredential credential = MongoCredential.createCredential("testUser", "czsb", "testPass".toCharArray());
        settingsBuilder.credential(credential);

        //传入服务器实例
        settingsBuilder.applyToClusterSettings(
                builder -> builder.hosts(servers));
        //构建 Client 实例
        MongoClient mongoClient = MongoClients.create(settingsBuilder.build());


        //获得数据库对象
        MongoDatabase database = mongoClient.getDatabase("czsb");

        //获得集合
        MongoCollection collection = database.getCollection("aaa");

    //异步返回Publisher
    //        FindPublisher publisher = collection.find();


//订阅实现
        SubscriberUtils subscriber = new SubscriberUtils(1);
        collection.find().subscribe(subscriber);
        //结果处理
        try {
            subscriber.get(15L, TimeUnit.SECONDS).forEach( d -> {
                System.out.println("Document:" + ((Document)d).toJson());
            });
        }catch (Throwable e){
            e.printStackTrace();
        }


    }
}
